<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程" prop="courseId">
        <!-- <el-input v-model="queryParams.courseId" placeholder="请输入课程id" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select @change="selectCourse" v-model="queryParams.courseId"  placeholder="请选择课程" style="width: 100%;">
          <el-option
            v-for="dict in courseList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          >
          </el-option>
        </el-select>




      </el-form-item>

      <el-form-item label="课程章节" prop="packageId">
        <el-select @change="selectCoursePackage" v-model="queryParams.packageId" placeholder="请选择章节" style="width: 100%;">
          <el-option
            v-for="dict in coursePackageList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          >
          </el-option>
        </el-select>




      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['yljf:ExerciseQuestion:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['yljf:ExerciseQuestion:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['yljf:ExerciseQuestion:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['yljf:ExerciseQuestion:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ExerciseQuestionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column width="250" label="课程" align="center" prop="courseName" />
      <el-table-column width="200" label="章节" align="center" prop="packageName" />
      <el-table-column label="题目" align="left" prop="questionId" >
        <template slot-scope="scope">
          <div class="cell-wrap">
            <div class="cell-content">{{scope.row.questionTitle}}</div>
            <div class="pick-item" v-for="item in scope.row.questionOptionsList">{{item}}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['yljf:ExerciseQuestion:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['yljf:ExerciseQuestion:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改练习题对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程" prop="courseId">
          <!-- <el-input v-model="form.courseId" placeholder="请输入课程id" /> -->

          <el-select @change="selectCourse" v-model="form.courseId"  placeholder="请选择课程" style="width: 100%;">
            <el-option
              v-for="dict in courseList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
          <!-- </el-form-item> -->
        </el-form-item>

        <el-form-item label="章节" prop="packageId">

          <el-select v-model="form.packageId"  placeholder="请选择章节" style="width: 100%;">
            <el-option
              v-for="dict in coursePackageList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
          <!-- </el-form-item> -->
        </el-form-item>

        <el-form-item label="题目" prop="questionId">
          <el-table ref="questionTable" class="questionTable" height="270" :data="baseQuestionBankList" @select="baseSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column width="60" label="id" align="center" prop="id" />
            <el-table-column width="280" label="题目" align="center" prop="questionTitle" >
               <template slot-scope="scope">
                 <div class="cell-wrap">
                   <div class="question-content">{{scope.row.questionTitle}}</div>
                   <div class="pick-item" v-for="item in scope.row.questionOptionsList">{{item}}</div>
                 </div>
               </template>
             </el-table-column>
             <el-table-column width="80" label="正确答案" align="center" prop="correctAnswer" />
          </el-table>

          <pagination
            layout="total, prev, pager, next"
            v-show="questionTotal>0"
            :total="questionTotal"
            :page.sync="questionQueryParams.pageNum"
            :limit.sync="questionQueryParams.pageSize"
            @pagination="getListBaseQuestionBank"
          />

          <!-- <el-input v-model="form.questionId" placeholder="请输入题目id" /> -->
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number  v-model="form.sort" controls-position="right" placeholder="请输入排序" :min="1" :max="100"></el-input-number>
          <!-- <el-input v-model="form.sort" placeholder="请输入排序" /> -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listExerciseQuestion,
    getExerciseQuestion,
    delExerciseQuestion,
    addExerciseQuestion,
    updateExerciseQuestion
  } from "@/api/yljf/ExerciseQuestion";
  import {
    listCourse_package,
  } from "@/api/yljf/course_package";
  import {
    listCourse
  } from "@/api/yljf/course";
  import {
    listBaseQuestionBank
  } from "@/api/yljf/baseQuestionBank";


  export default {
    name: "ExerciseQuestion",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 练习题表格数据
        ExerciseQuestionList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          courseId: null,
          packageId: null,
          questionId: null,
          sort: null,
        },
        questionTotal:0,
        questionQueryParams:{
          pageNum: 1,
          pageSize: 10,
        },

        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        courseList: [],
        courseObj:{},
        coursePackageList: [],
        coursePackageObj:{},

        baseQuestionBankList:[]
      };
    },
    created() {
      this.getListCourse()
      this.getListPackage()
      this.getListBaseQuestionBank()

    },
    methods: {
      /** 查询练习题列表 */
      getList() {
        this.loading = true;
        listExerciseQuestion(this.queryParams).then(response => {
          console.log(this.courseObj,this.coursePackageObj)
          this.ExerciseQuestionList = response.rows.map(item=>{
            item.courseName = this.courseObj[item.courseId]
            item.packageName = this.coursePackageObj[item.packageId]
            item.questionOptionsList = this.getQuestionOptionsList(JSON.parse(item.questionOptions))
            // this.baseQuestionBankList = response.rows.map(item=>{
            //   item.questionOptionsList = this.getQuestionOptionsList(JSON.parse(item.questionOptions))
            //   return item
            // });
            return item
          });
          this.total = response.total;
          this.loading = false;
          console.log(this.ExerciseQuestionList)
        });



      },

      getListBaseQuestionBank() {
        listBaseQuestionBank(this.questionQueryParams).then(response => {

          this.baseQuestionBankList = response.rows.map(item=>{
            item.questionOptionsList = this.getQuestionOptionsList(JSON.parse(item.questionOptions))
            return item
          });

          this.questionTotal = response.total;
          console.log(response)
        })
      },

      getQuestionOptionsList(questionOptions){
        var arr = []
        for (var key in questionOptions) {
          arr.push(key+'.'+questionOptions[key])
        }
        return arr
      },
      // 多选框选中数据
      baseSelectionChange(selection) {
        console.log(selection)
        if(selection.length == 0){
          this.form.questionId = null
        } else {
          var select = selection[selection.length - 1]
          if(selection.length > 1){
            this.$refs.questionTable.clearSelection();
            this.$refs.questionTable.toggleRowSelection(select);
          }
          this.form.questionId = select.id
        }

      },


      getListCourse() {
        listCourse({
          pageNum: 1,
          pageSize: 200,
        }).then(response => {
          // console.log(response.rows.le)
          this.courseObj = {}
          this.courseList = response.rows.map((item) => {
            this.courseObj[item.id] = item.name
            return {
              value: item.id,
              label: item.name
            }
          })

          // this.courseList = this.courseList.concat(this.courseList,this.courseList)
        });
      },

      getListPackage() {
        listCourse_package({
          pageNum: 1,
          pageSize: 200,
        }).then(response => {
          this.coursePackageObj = {}
          response.rows.forEach((item) => {
            this.coursePackageObj[item.id] = item.name
          })

          this.getList();

          // console.log(res)
        })


      },



      selectCourse(courseId) {
        listCourse_package({
          courseId
        }).then(response => {
          this.coursePackageList = response.rows.map((item) => {
            return {
              value: item.id,
              label: item.name
            }
          })

          // console.log(res)
        })


      },

      selectCoursePackage(id) {
        console.log(id)
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          courseId: null,
          packageId: null,
          questionId: null,
          sort: null,
          createTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加练习题";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getExerciseQuestion(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改练习题";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {

            this.$refs.questionTable.clearSelection();

            if (this.form.id != null) {
              updateExerciseQuestion(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addExerciseQuestion(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除练习题编号为"' + ids + '"的数据项？').then(function() {
          return delExerciseQuestion(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('yljf/ExerciseQuestion/export', {
          ...this.queryParams
        }, `ExerciseQuestion_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>

<style lang="scss" scoped>
  .question-content{
      // display: -webkit-box;
      // -webkit-box-orient: vertical;
      // -webkit-line-clamp: 3; /* 限制行数为3 */
      // overflow: hidden;
      display: flex;
      text-align: left;
  }

  .pick-item{
    display: flex;
  }


  ::v-deep{
    .questionTable thead .el-checkbox{
      display: none;
    }

    .el-dialog__body{
      padding-bottom: 0;
    }
  }
</style>
